package com.example.spring_java_oj.controller;

import com.example.spring_java_oj.model.Result;
import com.example.spring_java_oj.model.UserInfo;
import com.example.spring_java_oj.service.UserInfoAmountService;
import com.example.spring_java_oj.service.userInfo.UserInfoService;
import com.example.spring_java_oj.service.UserLoginService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserIndoController {

//    @Autowired
//    private UserInfoService userInfoService;

    @Autowired
    private UserInfoAmountService userInfoAmountService;

    @Autowired
    private UserLoginService userLoginService;

    @RequestMapping("/login")
    public Result login(String username, String password,String captcha,HttpServletRequest request){
        String ret = userLoginService.login(username, password, captcha, request);
        if(ret == null){
            return Result.success("登录成功");
        }
        return Result.fail(ret);
    }
    /**
     * 获取登录用户的信息
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) throws JsonProcessingException {
//        1. 从token中获取用户ID
//        2. 根据用户ID, 获取用户信息
//        String token = request.getHeader("user_token");
//        Integer userId = JwtUtils.getUserIdFromToken(token);
//        if (userId==null){
//            return null;
//        }
        Integer userId = (Integer) request.getSession().getAttribute("id");
        //UserInfo userInfo = userInfoService.queryById(userId);
        UserInfo userInfo = userInfoAmountService.queryById(userId);
        //System.out.println(userInfo.toString());
        return userInfo;
    }

    @RequestMapping("/register")
    public boolean register(String username, String passwordA, String passwordB) throws JsonProcessingException {
        log.info("username: " + username + " password: " + passwordA);
        return userInfoAmountService.register(username, passwordA, passwordB);
    }

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        userLoginService.buildCheckImage(request,response);
    }


    /**
     * 获取登录用户的信息
     */
//    @RequestMapping("/getmanager")
//    public UserInfo getmanager(HttpServletRequest request){
//        //1. 从token中获取用户ID
//        //2. 根据用户ID, 获取用户信息
//        String token = request.getHeader("user_token");
//        Integer manager = JwtUtils.getUserManagerFromToken(token);
//        if (manager==null){
//            return null;
//        }
//        return userInfoService.;
//    }


}
